home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / Musique / Quod Libet / quodlibet-3.3.0-installer.exe / bin / fractions.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2014-12-31  |  19KB  |  530 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.7)
  3.  
  4. '''Rational, infinite-precision, real numbers.'''
  5. from __future__ import division
  6. from decimal import Decimal
  7. import math
  8. import numbers
  9. import operator
  10. import re
  11. __all__ = [
  12.     'Fraction',
  13.     'gcd']
  14. Rational = numbers.Rational
  15.  
  16. def gcd(a, b):
  17.     '''Calculate the Greatest Common Divisor of a and b.
  18.  
  19.     Unless b==0, the result will have the same sign as b (so that when
  20.     b is divided by it, the result comes out positive).
  21.     '''
  22.     while b:
  23.         a = b
  24.         b = a % b
  25.     return a
  26.  
  27. _RATIONAL_FORMAT = re.compile('\n    \\A\\s*                      # optional whitespace at the start, then\n    (?P<sign>[-+]?)            # an optional sign, then\n    (?=\\d|\\.\\d)                # lookahead for digit or .digit\n    (?P<num>\\d*)               # numerator (possibly empty)\n    (?:                        # followed by\n       (?:/(?P<denom>\\d+))?    # an optional denominator\n    |                          # or\n       (?:\\.(?P<decimal>\\d*))? # an optional fractional part\n       (?:E(?P<exp>[-+]?\\d+))? # and optional exponent\n    )\n    \\s*\\Z                      # and optional whitespace to finish\n', re.VERBOSE | re.IGNORECASE)
  28.  
  29. class Fraction(Rational):
  30.     """This class implements rational numbers.
  31.  
  32.     In the two-argument form of the constructor, Fraction(8, 6) will
  33.     produce a rational number equivalent to 4/3. Both arguments must
  34.     be Rational. The numerator defaults to 0 and the denominator
  35.     defaults to 1 so that Fraction(3) == 3 and Fraction() == 0.
  36.  
  37.     Fractions can also be constructed from:
  38.  
  39.       - numeric strings similar to those accepted by the
  40.         float constructor (for example, '-2.3' or '1e10')
  41.  
  42.       - strings of the form '123/456'
  43.  
  44.       - float and Decimal instances
  45.  
  46.       - other Rational instances (including integers)
  47.  
  48.     """
  49.     __slots__ = ('_numerator', '_denominator')
  50.     
  51.     def __new__(cls, numerator = 0, denominator = None):
  52.         """Constructs a Fraction.
  53.  
  54.         Takes a string like '3/2' or '1.5', another Rational instance, a
  55.         numerator/denominator pair, or a float.
  56.  
  57.         Examples
  58.         --------
  59.  
  60.         >>> Fraction(10, -8)
  61.         Fraction(-5, 4)
  62.         >>> Fraction(Fraction(1, 7), 5)
  63.         Fraction(1, 35)
  64.         >>> Fraction(Fraction(1, 7), Fraction(2, 3))
  65.         Fraction(3, 14)
  66.         >>> Fraction('314')
  67.         Fraction(314, 1)
  68.         >>> Fraction('-35/4')
  69.         Fraction(-35, 4)
  70.         >>> Fraction('3.1415') # conversion from numeric string
  71.         Fraction(6283, 2000)
  72.         >>> Fraction('-47e-2') # string may include a decimal exponent
  73.         Fraction(-47, 100)
  74.         >>> Fraction(1.47)  # direct construction from float (exact conversion)
  75.         Fraction(6620291452234629, 4503599627370496)
  76.         >>> Fraction(2.25)
  77.         Fraction(9, 4)
  78.         >>> Fraction(Decimal('1.47'))
  79.         Fraction(147, 100)
  80.  
  81.         """
  82.         self = super(Fraction, cls).__new__(cls)
  83.         if denominator is None:
  84.             if isinstance(numerator, Rational):
  85.                 self._numerator = numerator.numerator
  86.                 self._denominator = numerator.denominator
  87.                 return self
  88.             if None(numerator, float):
  89.                 value = Fraction.from_float(numerator)
  90.                 self._numerator = value._numerator
  91.                 self._denominator = value._denominator
  92.                 return self
  93.             if None(numerator, Decimal):
  94.                 value = Fraction.from_decimal(numerator)
  95.                 self._numerator = value._numerator
  96.                 self._denominator = value._denominator
  97.                 return self
  98.             if None(numerator, basestring):
  99.                 m = _RATIONAL_FORMAT.match(numerator)
  100.                 numerator = None(int if m is None else '0')
  101.                 denom = m.group('denom')
  102.                 if denom:
  103.                     denominator = int(denom)
  104.                 else:
  105.                     denominator = 1
  106.                     decimal = m.group('decimal')
  107.                     if decimal:
  108.                         scale = 10 ** len(decimal)
  109.                         numerator = numerator * scale + int(decimal)
  110.                         denominator *= scale
  111.                     exp = m.group('exp')
  112.                     if exp:
  113.                         exp = int(exp)
  114.                         if exp >= 0:
  115.                             numerator *= 10 ** exp
  116.                         else:
  117.                             denominator *= 10 ** (-exp)
  118.                 if m.group('sign') == '-':
  119.                     numerator = -numerator
  120.                 
  121.             else:
  122.                 raise TypeError('argument should be a string or a Rational instance')
  123.         if isinstance(numerator, Rational) and isinstance(denominator, Rational):
  124.             numerator = numerator.numerator * denominator.denominator
  125.             denominator = denominator.numerator * numerator.denominator
  126.         else:
  127.             raise TypeError('both arguments should be Rational instances')
  128.         if None == 0:
  129.             raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
  130.         g = gcd(numerator, denominator)
  131.         self._numerator = numerator // g
  132.         self._denominator = denominator // g
  133.         return self
  134.  
  135.     
  136.     def from_float(cls, f):
  137.         '''Converts a finite float to a rational number, exactly.
  138.  
  139.         Beware that Fraction.from_float(0.3) != Fraction(3, 10).
  140.  
  141.         '''
  142.         if isinstance(f, numbers.Integral):
  143.             return cls(f)
  144.         if not None(f, float):
  145.             raise TypeError('%s.from_float() only takes floats, not %r (%s)' % (cls.__name__, f, type(f).__name__))
  146.         if math.isnan(f) or math.isinf(f):
  147.             raise TypeError('Cannot convert %r to %s.' % (f, cls.__name__))
  148.         return cls(*f.as_integer_ratio())
  149.  
  150.     from_float = classmethod(from_float)
  151.     
  152.     def from_decimal(cls, dec):
  153.         '''Converts a finite Decimal instance to a rational number, exactly.'''
  154.         Decimal = Decimal
  155.         import decimal
  156.         if isinstance(dec, numbers.Integral):
  157.             dec = Decimal(int(dec))
  158.         elif not isinstance(dec, Decimal):
  159.             raise TypeError('%s.from_decimal() only takes Decimals, not %r (%s)' % (cls.__name__, dec, type(dec).__name__))
  160.         if not dec.is_finite():
  161.             raise TypeError('Cannot convert %s to %s.' % (dec, cls.__name__))
  162.         (sign, digits, exp) = dec.as_tuple()
  163.         digits = int(''.join(map(str, digits)))
  164.         if sign:
  165.             digits = -digits
  166.         if exp >= 0:
  167.             return cls(digits * 10 ** exp)
  168.         return None(digits, 10 ** (-exp))
  169.  
  170.     from_decimal = classmethod(from_decimal)
  171.     
  172.     def limit_denominator(self, max_denominator = 1000000):
  173.         """Closest Fraction to self with denominator at most max_denominator.
  174.  
  175.         >>> Fraction('3.141592653589793').limit_denominator(10)
  176.         Fraction(22, 7)
  177.         >>> Fraction('3.141592653589793').limit_denominator(100)
  178.         Fraction(311, 99)
  179.         >>> Fraction(4321, 8765).limit_denominator(10000)
  180.         Fraction(4321, 8765)
  181.  
  182.         """
  183.         if max_denominator < 1:
  184.             raise ValueError('max_denominator should be at least 1')
  185.         if self._denominator <= max_denominator:
  186.             return Fraction(self)
  187.         (p0, q0, p1, q1) = None
  188.         n = self._numerator
  189.         d = self._denominator
  190.         while True:
  191.             a = n // d
  192.             q2 = q0 + a * q1
  193.             if q2 > max_denominator:
  194.                 break
  195.             (p0, q0, p1, q1) = (p1, q1, p0 + a * p1, q2)
  196.             n = d
  197.             d = n - a * d
  198.         k = (max_denominator - q0) // q1
  199.         bound1 = Fraction(p0 + k * p1, q0 + k * q1)
  200.         bound2 = Fraction(p1, q1)
  201.         if abs(bound2 - self) <= abs(bound1 - self):
  202.             return bound2
  203.         return None
  204.  
  205.     
  206.     def numerator(a):
  207.         return a._numerator
  208.  
  209.     numerator = property(numerator)
  210.     
  211.     def denominator(a):
  212.         return a._denominator
  213.  
  214.     denominator = property(denominator)
  215.     
  216.     def __repr__(self):
  217.         '''repr(self)'''
  218.         return 'Fraction(%s, %s)' % (self._numerator, self._denominator)
  219.  
  220.     
  221.     def __str__(self):
  222.         '''str(self)'''
  223.         if self._denominator == 1:
  224.             return str(self._numerator)
  225.         return None % (self._numerator, self._denominator)
  226.  
  227.     
  228.     def _operator_fallbacks(monomorphic_operator, fallback_operator):
  229.         '''Generates forward and reverse operators given a purely-rational
  230.         operator and a function from the operator module.
  231.  
  232.         Use this like:
  233.         __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op)
  234.  
  235.         In general, we want to implement the arithmetic operations so
  236.         that mixed-mode operations either call an implementation whose
  237.         author knew about the types of both arguments, or convert both
  238.         to the nearest built in type and do the operation there. In
  239.         Fraction, that means that we define __add__ and __radd__ as:
  240.  
  241.             def __add__(self, other):
  242.                 # Both types have numerators/denominator attributes,
  243.                 # so do the operation directly
  244.                 if isinstance(other, (int, long, Fraction)):
  245.                     return Fraction(self.numerator * other.denominator +
  246.                                     other.numerator * self.denominator,
  247.                                     self.denominator * other.denominator)
  248.                 # float and complex don\'t have those operations, but we
  249.                 # know about those types, so special case them.
  250.                 elif isinstance(other, float):
  251.                     return float(self) + other
  252.                 elif isinstance(other, complex):
  253.                     return complex(self) + other
  254.                 # Let the other type take over.
  255.                 return NotImplemented
  256.  
  257.             def __radd__(self, other):
  258.                 # radd handles more types than add because there\'s
  259.                 # nothing left to fall back to.
  260.                 if isinstance(other, Rational):
  261.                     return Fraction(self.numerator * other.denominator +
  262.                                     other.numerator * self.denominator,
  263.                                     self.denominator * other.denominator)
  264.                 elif isinstance(other, Real):
  265.                     return float(other) + float(self)
  266.                 elif isinstance(other, Complex):
  267.                     return complex(other) + complex(self)
  268.                 return NotImplemented
  269.  
  270.  
  271.         There are 5 different cases for a mixed-type addition on
  272.         Fraction. I\'ll refer to all of the above code that doesn\'t
  273.         refer to Fraction, float, or complex as "boilerplate". \'r\'
  274.         will be an instance of Fraction, which is a subtype of
  275.         Rational (r : Fraction <: Rational), and b : B <:
  276.         Complex. The first three involve \'r + b\':
  277.  
  278.             1. If B <: Fraction, int, float, or complex, we handle
  279.                that specially, and all is well.
  280.             2. If Fraction falls back to the boilerplate code, and it
  281.                were to return a value from __add__, we\'d miss the
  282.                possibility that B defines a more intelligent __radd__,
  283.                so the boilerplate should return NotImplemented from
  284.                __add__. In particular, we don\'t handle Rational
  285.                here, even though we could get an exact answer, in case
  286.                the other type wants to do something special.
  287.             3. If B <: Fraction, Python tries B.__radd__ before
  288.                Fraction.__add__. This is ok, because it was
  289.                implemented with knowledge of Fraction, so it can
  290.                handle those instances before delegating to Real or
  291.                Complex.
  292.  
  293.         The next two situations describe \'b + r\'. We assume that b
  294.         didn\'t know about Fraction in its implementation, and that it
  295.         uses similar boilerplate code:
  296.  
  297.             4. If B <: Rational, then __radd_ converts both to the
  298.                builtin rational type (hey look, that\'s us) and
  299.                proceeds.
  300.             5. Otherwise, __radd__ tries to find the nearest common
  301.                base ABC, and fall back to its builtin type. Since this
  302.                class doesn\'t subclass a concrete type, there\'s no
  303.                implementation to fall back to, so we need to try as
  304.                hard as possible to return an actual value, or the user
  305.                will get a TypeError.
  306.  
  307.         '''
  308.         
  309.         def forward(a, b):
  310.             if isinstance(b, (int, long, Fraction)):
  311.                 return monomorphic_operator(a, b)
  312.             if None(b, float):
  313.                 return fallback_operator(float(a), b)
  314.             if None(b, complex):
  315.                 return fallback_operator(complex(a), b)
  316.             return None
  317.  
  318.         forward.__name__ = '__' + fallback_operator.__name__ + '__'
  319.         forward.__doc__ = monomorphic_operator.__doc__
  320.         
  321.         def reverse(b, a):
  322.             if isinstance(a, Rational):
  323.                 return monomorphic_operator(a, b)
  324.             if None(a, numbers.Real):
  325.                 return fallback_operator(float(a), float(b))
  326.             if None(a, numbers.Complex):
  327.                 return fallback_operator(complex(a), complex(b))
  328.             return None
  329.  
  330.         reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
  331.         reverse.__doc__ = monomorphic_operator.__doc__
  332.         return (forward, reverse)
  333.  
  334.     
  335.     def _add(a, b):
  336.         '''a + b'''
  337.         return Fraction(a.numerator * b.denominator + b.numerator * a.denominator, a.denominator * b.denominator)
  338.  
  339.     (__add__, __radd__) = _operator_fallbacks(_add, operator.add)
  340.     
  341.     def _sub(a, b):
  342.         '''a - b'''
  343.         return Fraction(a.numerator * b.denominator - b.numerator * a.denominator, a.denominator * b.denominator)
  344.  
  345.     (__sub__, __rsub__) = _operator_fallbacks(_sub, operator.sub)
  346.     
  347.     def _mul(a, b):
  348.         '''a * b'''
  349.         return Fraction(a.numerator * b.numerator, a.denominator * b.denominator)
  350.  
  351.     (__mul__, __rmul__) = _operator_fallbacks(_mul, operator.mul)
  352.     
  353.     def _div(a, b):
  354.         '''a / b'''
  355.         return Fraction(a.numerator * b.denominator, a.denominator * b.numerator)
  356.  
  357.     (__truediv__, __rtruediv__) = _operator_fallbacks(_div, operator.truediv)
  358.     (__div__, __rdiv__) = _operator_fallbacks(_div, operator.div)
  359.     
  360.     def __floordiv__(a, b):
  361.         '''a // b'''
  362.         div = a / b
  363.         if isinstance(div, Rational):
  364.             return div.numerator // div.denominator
  365.         return None.floor(div)
  366.  
  367.     
  368.     def __rfloordiv__(b, a):
  369.         '''a // b'''
  370.         div = a / b
  371.         if isinstance(div, Rational):
  372.             return div.numerator // div.denominator
  373.         return None.floor(div)
  374.  
  375.     
  376.     def __mod__(a, b):
  377.         '''a % b'''
  378.         div = a // b
  379.         return a - b * div
  380.  
  381.     
  382.     def __rmod__(b, a):
  383.         '''a % b'''
  384.         div = a // b
  385.         return a - b * div
  386.  
  387.     
  388.     def __pow__(a, b):
  389.         '''a ** b
  390.  
  391.         If b is not an integer, the result will be a float or complex
  392.         since roots are generally irrational. If b is an integer, the
  393.         result will be rational.
  394.  
  395.         '''
  396.         if isinstance(b, Rational):
  397.             if b.denominator == 1:
  398.                 power = b.numerator
  399.                 if power >= 0:
  400.                     return Fraction(a._numerator ** power, a._denominator ** power)
  401.                 return None(a._denominator ** (-power), a._numerator ** (-power))
  402.             return float(a) ** float(b)
  403.         return float(a) ** b
  404.  
  405.     
  406.     def __rpow__(b, a):
  407.         '''a ** b'''
  408.         if b._denominator == 1 and b._numerator >= 0:
  409.             return a ** b._numerator
  410.         if None(a, Rational):
  411.             return Fraction(a.numerator, a.denominator) ** b
  412.         if None._denominator == 1:
  413.             return a ** b._numerator
  414.         return None ** float(b)
  415.  
  416.     
  417.     def __pos__(a):
  418.         '''+a: Coerces a subclass instance to Fraction'''
  419.         return Fraction(a._numerator, a._denominator)
  420.  
  421.     
  422.     def __neg__(a):
  423.         '''-a'''
  424.         return Fraction(-(a._numerator), a._denominator)
  425.  
  426.     
  427.     def __abs__(a):
  428.         '''abs(a)'''
  429.         return Fraction(abs(a._numerator), a._denominator)
  430.  
  431.     
  432.     def __trunc__(a):
  433.         '''trunc(a)'''
  434.         if a._numerator < 0:
  435.             return -(-(a._numerator) // a._denominator)
  436.         return None._numerator // a._denominator
  437.  
  438.     
  439.     def __hash__(self):
  440.         '''hash(self)
  441.  
  442.         Tricky because values that are exactly representable as a
  443.         float must have the same hash as that float.
  444.  
  445.         '''
  446.         if self._denominator == 1:
  447.             return hash(self._numerator)
  448.         if None == float(self):
  449.             return hash(float(self))
  450.         return None((self._numerator, self._denominator))
  451.  
  452.     
  453.     def __eq__(a, b):
  454.         '''a == b'''
  455.         if isinstance(b, Rational):
  456.             if a._numerator == b.numerator:
  457.                 pass
  458.             return a._denominator == b.denominator
  459.         if None(b, numbers.Complex) and b.imag == 0:
  460.             b = b.real
  461.         if isinstance(b, float):
  462.             if math.isnan(b) or math.isinf(b):
  463.                 return 0 == b
  464.             return None == a.from_float(b)
  465.         return NotImplemented
  466.  
  467.     
  468.     def _richcmp(self, other, op):
  469.         '''Helper for comparison operators, for internal use only.
  470.  
  471.         Implement comparison between a Rational instance `self`, and
  472.         either another Rational instance or a float `other`.  If
  473.         `other` is not a Rational instance or a float, return
  474.         NotImplemented. `op` should be one of the six standard
  475.         comparison operators.
  476.  
  477.         '''
  478.         if isinstance(other, Rational):
  479.             return op(self._numerator * other.denominator, self._denominator * other.numerator)
  480.         if None(other, complex):
  481.             raise TypeError('no ordering relation is defined for complex numbers')
  482.         if isinstance(other, float):
  483.             if math.isnan(other) or math.isinf(other):
  484.                 return op(0, other)
  485.             return None(self, self.from_float(other))
  486.         return NotImplemented
  487.  
  488.     
  489.     def __lt__(a, b):
  490.         '''a < b'''
  491.         return a._richcmp(b, operator.lt)
  492.  
  493.     
  494.     def __gt__(a, b):
  495.         '''a > b'''
  496.         return a._richcmp(b, operator.gt)
  497.  
  498.     
  499.     def __le__(a, b):
  500.         '''a <= b'''
  501.         return a._richcmp(b, operator.le)
  502.  
  503.     
  504.     def __ge__(a, b):
  505.         '''a >= b'''
  506.         return a._richcmp(b, operator.ge)
  507.  
  508.     
  509.     def __nonzero__(a):
  510.         '''a != 0'''
  511.         return a._numerator != 0
  512.  
  513.     
  514.     def __reduce__(self):
  515.         return (self.__class__, (str(self),))
  516.  
  517.     
  518.     def __copy__(self):
  519.         if type(self) == Fraction:
  520.             return self
  521.         return None.__class__(self._numerator, self._denominator)
  522.  
  523.     
  524.     def __deepcopy__(self, memo):
  525.         if type(self) == Fraction:
  526.             return self
  527.         return None.__class__(self._numerator, self._denominator)
  528.  
  529.  
  530.